'use client';

import { useState, useRef, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Badge } from '@/components/ui/badge';
import {
  Send,
  Bot,
  User,
  Copy,
  ThumbsUp,
  ThumbsDown,
  RefreshCw,
  Menu,
  Loader2,
} from 'lucide-react';
import {
  useCurrentSession,
  useMessages,
  useIsLoading,
  useIsStreaming,
  useChatActions,
  useUIActions,
  useUser,
} from '@/store';
import { ChatMessage } from '@/types';
import { cn } from '@/lib/utils';

interface MessageItemProps {
  message: ChatMessage;
  isLast: boolean;
}

function MessageItem({ message, isLast }: MessageItemProps) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(message.content);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (error) {
      console.error('复制失败:', error);
    }
  };

  const isUser = message.role === 'user';
  const isAssistant = message.role === 'assistant';

  return (
    <div
      className={cn(
        'group flex gap-4 p-4',
        isUser ? 'bg-muted/30' : 'bg-background'
      )}
    >
      {/* 头像 */}
      <div
        className={cn(
          'flex-shrink-0 w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium',
          isUser
            ? 'bg-primary text-primary-foreground'
            : 'bg-muted text-muted-foreground'
        )}
      >
        {isUser ? <User className='h-4 w-4' /> : <Bot className='h-4 w-4' />}
      </div>

      {/* 消息内容 */}
      <div className='flex-1 min-w-0'>
        <div className='flex items-center gap-2 mb-1'>
          <span className='text-sm font-medium'>
            {isUser ? '你' : 'AI助手'}
          </span>
          <span className='text-xs text-muted-foreground'>
            {new Date(message.created_at).toLocaleTimeString()}
          </span>
        </div>

        <div className='prose prose-sm max-w-none'>
          <div className='whitespace-pre-wrap break-words'>
            {message.content}
          </div>
        </div>

        {/* RAG结果显示 */}
        {(() => {
          if (!isAssistant || !message.metadata?.rag_results || !Array.isArray(message.metadata.rag_results) || message.metadata.rag_results.length === 0) {
            return null;
          }
          
          return (
            <div className='mt-3 p-3 bg-muted/50 rounded-lg'>
              <div className='text-xs font-medium text-muted-foreground mb-2'>
                参考文档 ({message.metadata.rag_results.length})
              </div>
              <div className='space-y-2'>
                {(message.metadata.rag_results as unknown[])
                  .slice(0, 3)
                  .map((result: unknown, index: number) => {
                    const ragResult = result as { title?: string; content?: string; score?: number };
                    return (
                      <div key={index} className='text-xs'>
                        <div className='font-medium'>{ragResult.title || '未知文档'}</div>
                        <div className='text-muted-foreground truncate'>
                          {ragResult.content ? ragResult.content.substring(0, 100) + '...' : '无内容'}
                        </div>
                        <Badge variant='outline' className='text-xs mt-1'>
                          相似度: {((ragResult.score || 0) * 100).toFixed(1)}%
                        </Badge>
                      </div>
                    );
                  })}
              </div>
            </div>
          );
        })()}

        {/* 操作按钮 */}
        {isAssistant && (
          <div className='flex items-center gap-2 mt-2 opacity-0 group-hover:opacity-100 transition-opacity'>
            <Button
              variant='ghost'
              size='sm'
              className='h-6 px-2 text-xs'
              onClick={handleCopy}
            >
              <Copy className='h-3 w-3 mr-1' />
              {copied ? '已复制' : '复制'}
            </Button>
            <Button variant='ghost' size='sm' className='h-6 px-2 text-xs'>
              <ThumbsUp className='h-3 w-3' />
            </Button>
            <Button variant='ghost' size='sm' className='h-6 px-2 text-xs'>
              <ThumbsDown className='h-3 w-3' />
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}

function StreamingMessage() {
  return (
    <div className='flex gap-4 p-4 bg-background'>
      <div className='flex-shrink-0 w-8 h-8 rounded-full bg-muted text-muted-foreground flex items-center justify-center'>
        <Bot className='h-4 w-4' />
      </div>
      <div className='flex-1'>
        <div className='flex items-center gap-2 mb-1'>
          <span className='text-sm font-medium'>AI助手</span>
          <Loader2 className='h-3 w-3 animate-spin' />
        </div>
        <div className='flex items-center gap-2 text-sm text-muted-foreground'>
          <div className='flex gap-1'>
            <div
              className='w-2 h-2 bg-current rounded-full animate-bounce'
              style={{ animationDelay: '0ms' }}
            />
            <div
              className='w-2 h-2 bg-current rounded-full animate-bounce'
              style={{ animationDelay: '150ms' }}
            />
            <div
              className='w-2 h-2 bg-current rounded-full animate-bounce'
              style={{ animationDelay: '300ms' }}
            />
          </div>
          <span>正在思考中...</span>
        </div>
      </div>
    </div>
  );
}

export function ChatArea() {
  const user = useUser();
  const currentSession = useCurrentSession();
  const messages = useMessages();
  const isLoading = useIsLoading();
  const isStreaming = useIsStreaming();
  const {
    addMessage,
    setCurrentSession,
    setMessages,
    setIsLoading,
    setIsStreaming,
  } = useChatActions();
  const { toggleSidebar } = useUIActions();

  const [input, setInput] = useState('');
  const [useRAG, setUseRAG] = useState(true);
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);

  // 自动滚动到底部
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages, isStreaming]);

  // 加载会话消息
  useEffect(() => {
    if (currentSession) {
      loadMessages(currentSession.id);
    } else {
      setMessages([]);
    }
  }, [currentSession]);

  const loadMessages = async (sessionId: string) => {
    try {
      const response = await fetch(`/api/chat?sessionId=${sessionId}`);
      const data = await response.json();

      if (data.success) {
        setMessages(data.data);
      }
    } catch (error) {
      console.error('加载消息失败:', error);
    }
  };

  const handleSend = async () => {
    if (!input.trim() || isLoading || isStreaming) return;

    const message = input.trim();
    setInput('');

    // 添加用户消息到UI
    const userMessage: ChatMessage = {
      id: Date.now().toString(),
      session_id: currentSession?.id || '',
      role: 'user',
      content: message,
      timestamp: new Date().toISOString(),
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      metadata: {},
    };

    addMessage(userMessage);
    setIsStreaming(true);

    try {
      // 使用流式API
      const response = await fetch('/api/chat/stream', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          message,
          sessionId: currentSession?.id,
          userId: user?.id,
          useRAG,
        }),
      });

      if (!response.ok) {
        throw new Error('请求失败');
      }

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();
      let aiResponse = '';
      let sessionId = currentSession?.id;

      if (reader) {
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6);
              if (data === '[DONE]') {
                break;
              }

              try {
                const parsed = JSON.parse(data);

                switch (parsed.type) {
                  case 'session_created':
                    sessionId = parsed.session_id;
                    if (!currentSession && sessionId) {
                      setCurrentSession({
                        id: sessionId,
                        title: message.slice(0, 50),
                        user_id: user?.id || '',
                        created_at: new Date().toISOString(),
                        updated_at: new Date().toISOString(),
                        message_count: 0,
                        messages: [],
                        metadata: {},
                      });
                    }
                    break;

                  case 'content':
                    aiResponse += parsed.content;
                    // 更新流式消息显示
                    break;

                  case 'completed':
                    // 添加完整的AI响应
                    const aiMessage: ChatMessage = {
                      id: parsed.ai_message_id,
                      session_id: sessionId || '',
                      role: 'assistant',
                      content: aiResponse,
                      timestamp: new Date().toISOString(),
                      created_at: new Date().toISOString(),
                      updated_at: new Date().toISOString(),
                      metadata: {
                        rag_results: parsed.rag_results,
                        context_used: parsed.context_used,
                      },
                    };
                    addMessage(aiMessage);
                    break;
                }
              } catch (e) {
                // 忽略解析错误
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('发送消息失败:', error);
      // 添加错误消息
      const errorMessage: ChatMessage = {
        id: Date.now().toString(),
        session_id: currentSession?.id || '',
        role: 'assistant',
        content: '抱歉，发送消息时出现错误，请稍后重试。',
        timestamp: new Date().toISOString(),
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        metadata: { error: true },
      };
      addMessage(errorMessage);
    } finally {
      setIsStreaming(false);
    }
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <div className='flex flex-col h-full'>
      {/* 头部 */}
      <div className='flex items-center justify-between p-4 border-b border-border'>
        <div className='flex items-center gap-3'>
          <Button
            variant='ghost'
            size='sm'
            onClick={toggleSidebar}
            className='h-8 w-8 p-0 md:hidden'
          >
            <Menu className='h-4 w-4' />
          </Button>
          <div>
            <h2 className='font-semibold'>
              {currentSession?.title || '新对话'}
            </h2>
            <p className='text-sm text-muted-foreground'>
              {messages.length > 0
                ? `${messages.length} 条消息`
                : '开始新的对话'}
            </p>
          </div>
        </div>

        <div className='flex items-center gap-2'>
          <Button
            variant={useRAG ? 'default' : 'outline'}
            size='sm'
            onClick={() => setUseRAG(!useRAG)}
          >
            RAG {useRAG ? '开启' : '关闭'}
          </Button>
          <Button variant='ghost' size='sm'>
            <RefreshCw className='h-4 w-4' />
          </Button>
        </div>
      </div>

      {/* 消息区域 */}
      <ScrollArea className='flex-1'>
        <div className='max-w-4xl mx-auto'>
          {messages.length === 0 ? (
            <div className='flex items-center justify-center h-full min-h-[400px]'>
              <div className='text-center'>
                <Bot className='h-12 w-12 mx-auto mb-4 text-muted-foreground' />
                <h3 className='text-lg font-medium mb-2'>开始新对话</h3>
                <p className='text-muted-foreground mb-4'>
                  我是你的AI助手，可以帮你回答问题、分析文档内容。
                </p>
                <div className='flex flex-wrap gap-2 justify-center'>
                  <Badge variant='outline'>文档问答</Badge>
                  <Badge variant='outline'>内容分析</Badge>
                  <Badge variant='outline'>智能搜索</Badge>
                </div>
              </div>
            </div>
          ) : (
            <div>
              {messages.map((message, index) => (
                <MessageItem
                  key={message.id}
                  message={message}
                  isLast={index === messages.length - 1}
                />
              ))}
              {isStreaming && <StreamingMessage />}
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
      </ScrollArea>

      {/* 输入区域 */}
      <div className='border-t border-border p-4'>
        <div className='max-w-4xl mx-auto'>
          <div className='flex gap-2'>
            <div className='flex-1 relative'>
              <Textarea
                ref={textareaRef}
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={handleKeyDown}
                placeholder='输入你的问题...'
                className='min-h-[60px] max-h-[200px] resize-none pr-12'
                disabled={isLoading || isStreaming}
              />
              <Button
                onClick={handleSend}
                disabled={!input.trim() || isLoading || isStreaming}
                className='absolute right-2 bottom-2 h-8 w-8 p-0'
                size='sm'
              >
                {isLoading || isStreaming ? (
                  <Loader2 className='h-4 w-4 animate-spin' />
                ) : (
                  <Send className='h-4 w-4' />
                )}
              </Button>
            </div>
          </div>

          <div className='flex items-center justify-between mt-2 text-xs text-muted-foreground'>
            <div className='flex items-center gap-4'>
              <span>按 Enter 发送，Shift + Enter 换行</span>
              {useRAG && (
                <Badge variant='secondary' className='text-xs'>
                  RAG模式已启用
                </Badge>
              )}
            </div>
            <span>{input.length}/2000</span>
          </div>
        </div>
      </div>
    </div>
  );
}
